using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ShopPowerTemplate.Entities;
using ShopPowerTemplate.IoC;
using ShopPowerTemplate.Presentation.Mvc.Extensions;
using ShopPowerTemplate.Presentation.Mvc.Models;
using ShopPowerTemplate.Presentation.Mvc.ViewModels;
using ShopPowerTemplate.Services;

namespace ShopPowerTemplate.Presentation.Mvc.Controllers
{
	public partial class ProductControllerBase : BaseController
	{
		#region Members

        protected IProductService _productService;
        protected ISubcategoryService _subcategoryService;
        protected IImageService _imageService;
        protected IReviewService _reviewService;
        protected ICustomerService _customerService;
        protected IProductDetailService _productDetailService;

        #endregion

        #region Constructors

        public ProductControllerBase(IProductService productService, ISubcategoryService subcategoryService, IImageService imageService, IReviewService reviewService, ICustomerService customerService, IProductDetailService productDetailService)
        {
            _productService = productService;
            _subcategoryService = subcategoryService;
            _imageService = imageService;
            _reviewService = reviewService;
            _customerService = customerService;
            _productDetailService = productDetailService;
        }	

        #endregion

		#region Index

		// **************************************
        // URL: /Product
        // **************************************
		public virtual ActionResult Index()
		{
			IndexProductViewModel viewModel = new IndexProductViewModel();
			ViewBag.PageIndex = this.GetPageIndex();
            ViewBag.PageSize = this.GetPageSize();
			ViewBag.SearchValue = this.GetSearchValue();
		
			return View(viewModel);
		}

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Load(string sidx, string sord, int page, int rows, string search, int mode = 1)
        {
            string searchValue = this.GetSearchValue();
            OrderBy orderBy = this.GetOrderBy();
            int pageIndex = this.GetPageIndex();
            int pageSize = this.GetPageSize();

            if (mode == (int)JQGridActionEnum.DefaultLoad)
            {                
                pageSize = (pageIndex + 1) * pageSize;
                pageIndex = 0;
            }
            else if (mode == (int)JQGridActionEnum.ShowMoreResults)
            {
                pageIndex = page;
                this.SetPageIndex(pageIndex);
            }
            else if (mode == (int)JQGridActionEnum.CustomSearch)
            {
                searchValue = search;
                this.SetSearchValue(searchValue);
                pageIndex = 0;
                this.SetPageIndex(pageIndex);
                orderBy = new OrderBy("", true);
                this.SetOrderBy(orderBy);
            }

            if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                orderBy = new OrderBy(sidx, sord == "asc");
                this.SetOrderBy(orderBy);
            }

            List<Product> searchList = _productService.Search(searchValue, orderBy.Property, orderBy.Ascending, pageIndex, pageSize);
            int count = _productService.SearchCount(searchValue);
            
			if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                pageIndex = this.GetPageIndex();
            }

            var data = new
            {
                total = Math.Ceiling((float)count/(float)pageSize),        // Total pages
                page = pageIndex,      // Current page
                records = count,  // Total records
                rows = from product in searchList     // Row data
                       select new
                       {
                           id = product.Id,                
                           cell = new string[] {
						   
                                product.Name,
								product.Description,
								product.Price.ToString(),
								product.Tax.ToString(),
								product.Prominent? "1" : "0",
								product.Weight.ToString(),
								product.Discount.ToString(),
								product.IsInactive.HasValue && product.IsInactive.Value ? "1" : "0",
								product.Subcategory != null ? product.Subcategory.IdentityDescription : string.Empty
								
                           }
                       }
            };

            return Json(data);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Delete(int id)
        {
            try
            {
                _productService.Remove(id);
            }
            catch (RemoveException ex)
            {
                Response.StatusCode = 500;
                return Content(ex.Message);
            }
            return Content(string.Empty);
        }
		
		public virtual FileContentResult Report()
        {
            IList<Product> _productList = _productService.Search(this.GetSearchValue());            
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Name;Description;Price;Tax;Prominent;Weight;Discount;IsInactive;Subcategory");

            // rows
            foreach (Product product in _productList)
            {
                List<string> rowData = new List<string>() { product.Name, product.Description, product.Price.ToString(), product.Tax.ToString(), product.Prominent.ToString(), product.Weight.ToString(), product.Discount.ToString(), product.IsInactive.ToString(), product.Subcategory != null ? product.Subcategory.IdentityDescription : string.Empty };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "Product.csv");
        }
		

		#endregion

		#region Create

		// *******************************************
        // URL: /Product/Create
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Create()
        {
            Product product = new Product();
            CreateProductViewModel viewModel = Mapper.Map<Product, CreateProductViewModel>(product);
            List<Subcategory> allSubcategory = _subcategoryService.FindAll();
            viewModel.SubcategoryList = allSubcategory;
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Create(CreateProductViewModel productModel)
        {
            if (ModelState.IsValid)
            {
                Product product = new Product();
                AutoMapper.Mapper.Map<CreateProductViewModel, Product>(productModel, product);
 

				_productService.Add(product);

                return RedirectToAction("Edit", new { id = product.Id});
            }
            else
            {
				List<Subcategory> allSubcategory = _subcategoryService.FindAll();
				productModel.SubcategoryList = allSubcategory;

                return View(productModel);
            }
		}
		

		#endregion

		#region Edit

		// *******************************************
        // URL: /Product/Edit/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Edit(int id)
        {
            Product product = _productService.Find(id);
            EditProductViewModel viewModel = Mapper.Map<Product, EditProductViewModel>(product);
            List<Subcategory> allSubcategory = _subcategoryService.FindAll();
            viewModel.SubcategoryList = allSubcategory;
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Edit(EditProductViewModel productModel)
        {
            if (ModelState.IsValid)
            {
                Product product = _productService.Find(productModel.Id);
                AutoMapper.Mapper.Map<EditProductViewModel, Product>(productModel, product);
                
				_productService.Change(product);

                return RedirectToAction("Index");
            }
            else
            {
				List<Subcategory> allSubcategory = _subcategoryService.FindAll();
				productModel.SubcategoryList = allSubcategory;

                return View(productModel);
            }
		}
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult LoadImages(string sidx, string sord, int page, int rows, string search, int mode = 1, int masterId = 0)
        {
			Product currentProduct = _productService.Find(masterId);
            List<Image> list = currentProduct.Images.ToList();
			int count = list.Count();

			var data = new
            {
                total = 1,        // Total pages
                page = 1,      // Current page
                records = count,  // Total records
                rows = from image in list     // Row data
                       select new
                       {
                           id = image.Id,                
                           cell = new string[] {
                                image.Name,
								image.Description,
								image.SortOrder.ToString()
                           }
                       }
            };

            // Return elements
            return Json(data);
        }

		public virtual ActionResult AddImages(int masterId = 0)
        {
            PopUpImageViewModel viewModel = new PopUpImageViewModel();

			viewModel.ProductId = masterId;
			ViewBag.MasterProperty = "Product";
            ViewBag.Name = "AddImages";

            return PartialView("~/Views/Image/PopUp.cshtml", viewModel);
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult AddImages(PopUpImageViewModel imageModel)
        {
            if (ModelState.IsValid)
            {
                Image images = new Image();
                AutoMapper.Mapper.Map<PopUpImageViewModel, Image>(imageModel, images);

				Product product = _productService.Find(images.Product.Id);
				_productService.AddImages(product, images);
                
				Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				ViewBag.MasterProperty = "Product";
            	ViewBag.Name = "AddImages";


				return PartialView("~/Views/Image/PopUp.cshtml", imageModel);
            }
        }	
		
		public virtual ActionResult EditImages(int id, int masterId = 0)
        {
			Image image = _imageService.Find(id);
            PopUpImageViewModel viewModel = Mapper.Map<Image, PopUpImageViewModel>(image);

			List<Product> allProduct = _productService.FindAll();
			viewModel.ProductId = masterId;
			ViewBag.MasterProperty = "Product";
            ViewBag.Name = "EditImages";

            return PartialView("~/Views/Image/PopUp.cshtml", viewModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult EditImages(PopUpImageViewModel imageModel)
        {
            if (ModelState.IsValid)
            {
                Image image = _imageService.Find(imageModel.Id);
                AutoMapper.Mapper.Map<PopUpImageViewModel, Image>(imageModel, image);

                _imageService.Change(image);

                Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				List<Product> allProduct = _productService.FindAll();
				imageModel.ProductList = allProduct;
				ViewBag.MasterProperty = "Product";

                return PartialView("~/Views/Image/PopUp.cshtml", imageModel);
            }
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual void DeleteImages(int id, int masterId = 0)
        {
			Image image = _imageService.Find(id);
			Product currentProduct = _productService.Find(masterId);

            _productService.RemoveImages(currentProduct, image);
        }
			
		public virtual FileContentResult ReportImages(int masterId = 0)
        {
			Product currentProduct = _productService.Find(masterId);
            IList<Image> _imagesList = currentProduct.Images.ToList();          
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Name;Description;SortOrder");

            // rows
            foreach (Image image in _imagesList)
            {
                List<string> rowData = new List<string>() { image.Name, image.Description, image.SortOrder.ToString() };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "Images.csv");
        }
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult LoadReviews(string sidx, string sord, int page, int rows, string search, int mode = 1, int masterId = 0)
        {
			Product currentProduct = _productService.Find(masterId);
            List<Review> list = currentProduct.Reviews.ToList();
			int count = list.Count();

			var data = new
            {
                total = 1,        // Total pages
                page = 1,      // Current page
                records = count,  // Total records
                rows = from review in list     // Row data
                       select new
                       {
                           id = review.Id,                
                           cell = new string[] {
                                review.Date.ToString(),
								review.Rating.ToString(),
								review.Comment,
								review.Customer != null ? review.Customer.IdentityDescription : string.Empty
                           }
                       }
            };

            // Return elements
            return Json(data);
        }

		public virtual ActionResult AddReviews(int masterId = 0)
        {
            PopUpReviewViewModel viewModel = new PopUpReviewViewModel();

			List<Customer> allCustomer = _customerService.FindAll();
			viewModel.CustomerList = allCustomer;
			viewModel.ProductId = masterId;
			ViewBag.MasterProperty = "Product";
            ViewBag.Name = "AddReviews";

            return PartialView("~/Views/Review/PopUp.cshtml", viewModel);
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult AddReviews(PopUpReviewViewModel reviewModel)
        {
            if (ModelState.IsValid)
            {
                Review reviews = new Review();
                AutoMapper.Mapper.Map<PopUpReviewViewModel, Review>(reviewModel, reviews);

				Product product = _productService.Find(reviews.Product.Id);
				_productService.AddReviews(product, reviews);
                
				Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				List<Customer> allCustomer = _customerService.FindAll();
				reviewModel.CustomerList = allCustomer;
				ViewBag.MasterProperty = "Product";
            	ViewBag.Name = "AddReviews";


				return PartialView("~/Views/Review/PopUp.cshtml", reviewModel);
            }
        }	
		
		public virtual ActionResult EditReviews(int id, int masterId = 0)
        {
			Review review = _reviewService.Find(id);
            PopUpReviewViewModel viewModel = Mapper.Map<Review, PopUpReviewViewModel>(review);

			List<Customer> allCustomer = _customerService.FindAll();
			List<Product> allProduct = _productService.FindAll();
			viewModel.CustomerList = allCustomer;
			viewModel.ProductId = masterId;
			ViewBag.MasterProperty = "Product";
            ViewBag.Name = "EditReviews";

            return PartialView("~/Views/Review/PopUp.cshtml", viewModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult EditReviews(PopUpReviewViewModel reviewModel)
        {
            if (ModelState.IsValid)
            {
                Review review = _reviewService.Find(reviewModel.Id);
                AutoMapper.Mapper.Map<PopUpReviewViewModel, Review>(reviewModel, review);

                _reviewService.Change(review);

                Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				List<Customer> allCustomer = _customerService.FindAll();
				List<Product> allProduct = _productService.FindAll();
				reviewModel.CustomerList = allCustomer;
				reviewModel.ProductList = allProduct;
				ViewBag.MasterProperty = "Product";

                return PartialView("~/Views/Review/PopUp.cshtml", reviewModel);
            }
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual void DeleteReviews(int id, int masterId = 0)
        {
			Review review = _reviewService.Find(id);
			Product currentProduct = _productService.Find(masterId);

            _productService.RemoveReviews(currentProduct, review);
        }
			
		public virtual FileContentResult ReportReviews(int masterId = 0)
        {
			Product currentProduct = _productService.Find(masterId);
            IList<Review> _reviewsList = currentProduct.Reviews.ToList();          
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Date;Rating;Comment;Customer");

            // rows
            foreach (Review review in _reviewsList)
            {
                List<string> rowData = new List<string>() { review.Date.ToString(), review.Rating.ToString(), review.Comment, review.Customer != null ? review.Customer.IdentityDescription : string.Empty };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "Reviews.csv");
        }
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult LoadProductDetails(string sidx, string sord, int page, int rows, string search, int mode = 1, int masterId = 0)
        {
			Product currentProduct = _productService.Find(masterId);
            List<ProductDetail> list = currentProduct.ProductDetails.ToList();
			int count = list.Count();

			var data = new
            {
                total = 1,        // Total pages
                page = 1,      // Current page
                records = count,  // Total records
                rows = from productDetail in list     // Row data
                       select new
                       {
                           id = productDetail.Id,                
                           cell = new string[] {
                                productDetail.Stock.ToString()
                           }
                       }
            };

            // Return elements
            return Json(data);
        }

		public virtual ActionResult AddProductDetails(int masterId = 0)
        {
            PopUpProductDetailViewModel viewModel = new PopUpProductDetailViewModel();

			viewModel.ProductId = masterId;
			ViewBag.MasterProperty = "Product";
            ViewBag.Name = "AddProductDetails";

            return PartialView("~/Views/ProductDetail/PopUp.cshtml", viewModel);
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult AddProductDetails(PopUpProductDetailViewModel productDetailModel)
        {
            if (ModelState.IsValid)
            {
                ProductDetail productDetails = new ProductDetail();
                AutoMapper.Mapper.Map<PopUpProductDetailViewModel, ProductDetail>(productDetailModel, productDetails);

				Product product = _productService.Find(productDetails.Product.Id);
				_productService.AddProductDetails(product, productDetails);
                
				Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				ViewBag.MasterProperty = "Product";
            	ViewBag.Name = "AddProductDetails";


				return PartialView("~/Views/ProductDetail/PopUp.cshtml", productDetailModel);
            }
        }	
		
		public virtual ActionResult EditProductDetails(int id, int masterId = 0)
        {
			ProductDetail productDetail = _productDetailService.Find(id);
            PopUpProductDetailViewModel viewModel = Mapper.Map<ProductDetail, PopUpProductDetailViewModel>(productDetail);

			List<Product> allProduct = _productService.FindAll();
			viewModel.ProductId = masterId;
			ViewBag.MasterProperty = "Product";
            ViewBag.Name = "EditProductDetails";

            return PartialView("~/Views/ProductDetail/PopUp.cshtml", viewModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult EditProductDetails(PopUpProductDetailViewModel productDetailModel)
        {
            if (ModelState.IsValid)
            {
                ProductDetail productDetail = _productDetailService.Find(productDetailModel.Id);
                AutoMapper.Mapper.Map<PopUpProductDetailViewModel, ProductDetail>(productDetailModel, productDetail);

                _productDetailService.Change(productDetail);

                Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				List<Product> allProduct = _productService.FindAll();
				productDetailModel.ProductList = allProduct;
				ViewBag.MasterProperty = "Product";

                return PartialView("~/Views/ProductDetail/PopUp.cshtml", productDetailModel);
            }
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual void DeleteProductDetails(int id, int masterId = 0)
        {
			ProductDetail productDetail = _productDetailService.Find(id);
			Product currentProduct = _productService.Find(masterId);

            _productService.RemoveProductDetails(currentProduct, productDetail);
        }
			
		public virtual FileContentResult ReportProductDetails(int masterId = 0)
        {
			Product currentProduct = _productService.Find(masterId);
            IList<ProductDetail> _productDetailsList = currentProduct.ProductDetails.ToList();          
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Stock");

            // rows
            foreach (ProductDetail productDetail in _productDetailsList)
            {
                List<string> rowData = new List<string>() { productDetail.Stock.ToString() };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "ProductDetails.csv");
        }
		

		#endregion

		#region Details

		// *******************************************
        // URL: /Product/Details/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Details(int id)
        {
            Product product = _productService.Find(id);
            DetailsProductViewModel viewModel = Mapper.Map<Product, DetailsProductViewModel>(product);
            
			return View(viewModel);
        }
		

		#endregion
	}
}
